package com.ziyia.sharedpreferencestest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private Button saveButton, restoreButton;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();

        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor data = getSharedPreferences("data", Context.MODE_PRIVATE).edit();
                data.putString("name", "年少有为");
                data.putInt("age", 18);
                data.apply();
            }
        });

        restoreButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences data = getSharedPreferences("data", Context.MODE_PRIVATE);
                String name = data.getString("name", "");
                Integer age = data.getInt("age", 0);
                Toast.makeText(MainActivity.this, "name = " + name + "，age = " + age, Toast.LENGTH_SHORT).show();

            }
        });

    }

    private void init() {
        saveButton = findViewById(R.id.saveButton);
        restoreButton = findViewById(R.id.restoreButton);
    }
}